package com.catazy.base.presentation.ext

import androidx.fragment.app.Fragment
import androidx.navigation.NavDirections
import androidx.navigation.NavOptions
import androidx.navigation.fragment.findNavController
import com.catazy.base.R
import timber.log.Timber


/**
 * 安全导航
 * @param directions 导航的方向和参数
 * @param navOptions 配置导航选项（如动画、弹出堆栈等）
 */
fun Fragment.navigateSafe(directions: NavDirections, navOptions: NavOptions? = null) {
    if (canNavigate()) findNavController().navigate(directions, navOptions)
}

/**
 * 判断是否可以导航
 */
fun Fragment.canNavigate(): Boolean {
    val navController = findNavController()
    // 返回当前指向的目的地的 ID
    val destinationIdInNavController = navController.currentDestination?.id
    // 获取当前fragment的目的地ID
    val destinationIdOfThisFragment = view?.getTag(R.id.tag_navigation_destination_id) ?: destinationIdInNavController
    // 如果 NavController 的当前目的地 ID 与 Fragment 的目的地 ID 相同，则认为当前 Fragment 是活动的，允许导航
    return if (destinationIdInNavController == destinationIdOfThisFragment) {
        view?.setTag(R.id.tag_navigation_destination_id, destinationIdOfThisFragment)
        true
    } else {
        Timber.d("May not navigate: current destination is not the current fragment.")
        false
    }
}